class Solution {
    public String reverseWords(String s) {
        StringBuffer sb = new StringBuffer();
        s = s.trim();
        int i = s.length() - 1, j = i;
        while(i >= 0){
            while(i >= 0 && s.charAt(i) != ' ') i--;
            sb.append(s.substring(i + 1,j + 1)).append(" ");
            while(i >= 0 && s.charAt(i) == ' ') i--;
            j = i;
        }
        return sb.toString().trim();
    }
}